/*
 * @Author: taosong 2289713738@qq.com
 * @Date: 2023-12-26 18:57:54
 * @LastEditors: taosong 2289713738@qq.com
 * @LastEditTime: 2023-12-26 20:44:08
 * @FilePath: \ele-h5\src\use\useAsync.ts
 * @Description:
 *
 * Copyright (c) 2023 by ${git_name_email}, All Rights Reserved.
 */
import { type UnwrapRef, ref } from 'vue'

export const useAsync = <T>(asyncFn: () => Promise<T>, initValue: T, immediate: boolean) => {
  const pending = ref(false)
  const data = ref(initValue)
  const error = ref(null)
  const execute = () => {
    pending.value = true
    error.value = null
    return asyncFn()
      .then((res) => {
        data.value = res as UnwrapRef<T>
        pending.value = false
      })
      .catch((err) => {
        error.value = err
        pending.value = false
      })
  }

  // 立刻执行
  if (immediate) {
    execute()
  }

  return {
    pending,
    data,
    error,
    execute
  }
}
